package com.wushi.lenovo.asia5b.app_ui.credit.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.ListPopupWindow;
import android.support.v7.widget.SwitchCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.mvp.base.BaseMvpFragment;
import com.mvp.base.model.ResultModel;
import com.mvp.ui.view.BaseTextWatcher;
import com.mvp.utils.DisplayUtils;
import com.mvp.utils.StringUtils;
import com.mvp.utils.ToastUtil;
import com.mvp.utils.https.MapHelper;
import com.wushi.lenovo.asia5b.R;
import com.wushi.lenovo.asia5b.app_config.CommonConstant;
import com.wushi.lenovo.asia5b.app_di.APPComponentFactory;
import com.wushi.lenovo.asia5b.app_di.credit.mvpview.CardFragmentView;
import com.wushi.lenovo.asia5b.app_di.credit.presenter.CardFragmentPresenter;
import com.wushi.lenovo.asia5b.app_model.credit.bean.ThirdTopupType;
import com.wushi.lenovo.asia5b.app_model.credit.bean.TopupInfoBean;
import com.wushi.lenovo.asia5b.app_model.other.PopupItemTextIml;
import com.wushi.lenovo.asia5b.app_model.other.UserInfo;
import com.wushi.lenovo.asia5b.app_model.other.WebUrlType;
import com.wushi.lenovo.asia5b.app_ui.h5.TopupThirdActivity;
import com.wushi.lenovo.asia5b.app_utils.eye.EyeUtils;
import com.wushi.lenovo.asia5b.app_utils.eye.PopupListAdapter;
import com.wushi.lenovo.asia5b.app_utils.eye.PopupWindowHelper;
import com.wushi.lenovo.asia5b.app_utils.helper.CacheHelper;
import com.wushi.lenovo.asia5b.app_widget.ErrorTextView;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

import static timber.log.Timber.d;

/**
 * Created by zhangyuncai on 2019/1/15.
 * 信用卡充值
 */
public class CardFragment extends BaseMvpFragment<CardFragmentView, CardFragmentPresenter>
        implements CardFragmentView {


    //编辑充值金额模块
    @BindView(R.id.et_card_amount)
    public EditText et_card_amount;//编辑 充值金额
    @BindView(R.id.tv_card_amount_error)
    public ErrorTextView tv_card_amount_error;
    @BindView(R.id.ll_card_price_vessel)
    public LinearLayout ll_card_price_vessel;//编辑 充值金额 的容器

    //当有信用卡记录信息的模块
    @BindView(R.id.ll_card_hascard_vessel)
    public LinearLayout ll_card_hascard_vessel;//记录信息控件的最外层的容器
    @BindView(R.id.ll_card_selectcard)
    public LinearLayout ll_card_selectcard;//选中记录信息的容器
    @BindView(R.id.iv_card_visaicon)
    public ImageView iv_card_visaicon;//记录信息信用卡的卡类型icon
    @BindView(R.id.tv_card_oldnum)
    public TextView tv_card_oldnum;//记录信息信用卡的编号
    @BindView(R.id.cb_card_visa)
    public RadioButton cb_card_visa;//选中记录信息的复选框
    @BindView(R.id.ll_card_selectcard_vessel)
    public LinearLayout ll_card_selectcard_vessel;//记录信息信用卡的校验码容器
    @BindView(R.id.et_card_cvv2)
    public EditText et_card_cvv2;//记录信息信用卡的校验码编辑控件
    @BindView(R.id.tv_card_mm_error2)
    public ErrorTextView tv_card_mm_error2;
    @BindView(R.id.ll_card_newcard)

    //新信用卡的模块
    public LinearLayout ll_card_newcard;//新信用卡选择控件的容器
    @BindView(R.id.cb_card_newcard)
    public RadioButton cb_card_newcard;//新信用卡选择控件的复选框
    @BindView(R.id.ll_card_newcard_vessel)
    public LinearLayout ll_card_newcard_vessel;//新信用卡的所有信息容器
    @BindView(R.id.et_card_number)
    public EditText et_card_number;//新信用卡的卡号编辑控件
    @BindView(R.id.tv_card_number_error)
    public ErrorTextView tv_card_number_error;
    @BindView(R.id.et_card_name)
    public EditText et_card_name;//新信用卡的卡名称编辑控件
    @BindView(R.id.tv_card_name_error)
    public ErrorTextView tv_card_name_error;
    @BindView(R.id.iv_card_cardicon)
    public ImageView iv_card_cardicon;//新信用卡的卡类型icon
    @BindView(R.id.tv_card_mm)
    public TextView tv_card_mm;//新信用卡的卡有效期月份
    @BindView(R.id.tv_card_mm_error)
    public ErrorTextView tv_card_mm_error;
    @BindView(R.id.tv_card_yy)
    public TextView tv_card_yy;//新信用卡的卡有效期年份
    @BindView(R.id.et_card_cvv)
    public EditText et_card_cvv;//新信用卡的卡校验码编辑框


    @BindView(R.id.cb_card_save)
    public SwitchCompat cb_card_save;//是否记录卡的信息
    @BindView(R.id.bt_card_submit)
    public Button bt_card_submit;//提交
    @BindView(R.id.tv_card_notice)
    public TextView tv_card_notice;//超链接控件


    public String mmText;
    public String yyText;

    public PopupListAdapter<PopupItemTextIml> yearAdapter;
    public PopupListAdapter<PopupItemTextIml> monthAdapter;
    public ListPopupWindow popupWindowYear;
    public ListPopupWindow popupWindowMonth;

    public ThirdTopupType thirdTopupType = ThirdTopupType.thirdtopup_by_creditcard;

    @Override
    protected void constructComponent() {
        APPComponentFactory.getAppBaseComponent().inject(this);
    }

    @Override
    protected int getLayout() {
        return R.layout.fragment_card;
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        setView();
        initView();
        initEvent();
    }

    @Override
    protected void lazyFetchData() {
        initData();
    }

    @Override
    protected void initView() {

        List<PopupItemTextIml> yearList = new ArrayList<>();
        for (int j = 19; j <= 89; j++) {
            yearList.add(new PopupItemTextIml(j + ""));
        }
        yearAdapter = new PopupListAdapter<>(getContext(), R.layout.item_popupitem_card_adapter, yearList);
        popupWindowYear = PopupWindowHelper.getListPopupWindow(getContext(), yearAdapter
                , tv_card_yy, DisplayUtils.dip2px(getContext(), 250));

        List<PopupItemTextIml> monthList = new ArrayList<>();
        String[] stringArray = getResources().getStringArray(R.array.month_string_array3);
        for (String s : stringArray) {
            monthList.add(new PopupItemTextIml(s));
        }
        monthAdapter = new PopupListAdapter<>(getContext(), R.layout.item_popupitem_card_adapter, monthList);
        popupWindowMonth = PopupWindowHelper.getListPopupWindow(getContext(), monthAdapter
                , tv_card_mm, DisplayUtils.dip2px(getContext(), 250));
    }


    protected void setView() {
        UserInfo userInfo = UserInfo.getUserInfo();
        //编辑充值金额
        //设置最低充值额度
        String creditCard_minimum_value = CacheHelper.loadCreditMinByLocal().getCreditCard_minimum_value();
        et_card_amount.setHint(String.format(getString(R.string.topup_notice_min), creditCard_minimum_value));
        //记录信用卡
        //新信用卡
        if (TextUtils.isEmpty(userInfo.getCard_number())) {//没有信用卡记录
            //记录信息
            ll_card_hascard_vessel.setVisibility(View.GONE);
            ll_card_newcard_vessel.setVisibility(View.VISIBLE);
            cb_card_save.setChecked(true);
        } else {//有信用卡记录
            ll_card_hascard_vessel.setVisibility(View.VISIBLE);
            ll_card_newcard_vessel.setVisibility(View.GONE);
            tv_card_oldnum.setText(userInfo.getCard_number());
            cb_card_save.setChecked(false);
            String numberCardType = getPresenter().getNumberCardType(userInfo.getCard_number());
            if (TextUtils.isEmpty(numberCardType)) {
                iv_card_visaicon.setVisibility(View.GONE);
            } else {
                iv_card_visaicon.setVisibility(View.VISIBLE);
                iv_card_visaicon.setImageResource(TextUtils.equals(numberCardType, "Visa") ? R.drawable.icon_visa : R.drawable.ic_master);
            }
            setHasCardGone(true);

        }
        //超链接
        EyeUtils.setLinkText(getContext(), getString(R.string.topup_notice), getString(R.string.termsconditions), tv_card_notice, WebUrlType.termsconditions_creditcard);
    }

    //设置显示隐藏
    protected void setHasCardGone(boolean isHasCard) {
        cb_card_visa.setChecked(isHasCard);
        cb_card_newcard.setChecked(!cb_card_visa.isChecked());
        if (cb_card_visa.isChecked()) {
            ll_card_selectcard_vessel.setVisibility(View.VISIBLE);
            ll_card_newcard_vessel.setVisibility(View.GONE);
        } else {
            ll_card_selectcard_vessel.setVisibility(View.GONE);
            ll_card_newcard_vessel.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void initData() {

    }

    /**
     * 获取最低充值额度
     *
     * @return
     */
    protected float getAmount() {
        return StringUtils.parseFloat(et_card_amount.getText().toString().trim());
    }

    protected int getCheckout_log_id() {
        return 0;
    }

    protected TopupInfoBean getTopupInfoBean() {
        return null;
    }

    protected void submit() {
//        Mastercard
//  Card No. : 5239380090174101
//  Expired Date: 0825
//  CVV2: 894
//        OTP Code Testing: 123123 
        boolean b = false;
//        et_card_number.setText("5239380090174101");
        String numberText = null;
        float amount = 0;
        int saveCreditCard = 0;
        String cardName = null;
        String cardExp = null;
        String cvvText = null;
        UserInfo userInfo = UserInfo.getUserInfo();
        if (cb_card_visa.isChecked()) {
            cardName = userInfo.getCard_name();
            cardExp = userInfo.getCard_exp();
            cvvText = et_card_cvv2.getText().toString().trim();
            numberText = userInfo.getCard_number();
            saveCreditCard = 1;
        } else {
            cardName = et_card_name.getText().toString().trim();
            cvvText = et_card_cvv.getText().toString().trim();
            if (!TextUtils.isEmpty(mmText) && !TextUtils.isEmpty(yyText)) {
                cardExp = mmText + yyText;
            }
            numberText = et_card_number.getText().toString().trim();
            saveCreditCard = cb_card_save.isChecked() ? 1 : 0;
        }
        amount = getAmount();


//        if (GlobalValue.isDebug) {
//            cardExp = "0325";
//            numberText = "4553 8809 0009 5108";
//            cvvText = "464";
//            if (thirdTopupType != ThirdTopupType.thirdtopup_from_orderpayment_by_creditcard &&
//                    thirdTopupType != ThirdTopupType.thirdtopup_from_orderpayment_ins_by_creditcard) {
//                amount = 222;
//            }
//        }

        d("--->>>>>>>>---amount:" + amount);
        if (amount < CacheHelper.loadCreditMinByLocal().getCreditCard_minimum_valueF()) {
            tv_card_amount_error.setVisibility(View.VISIBLE);
            b = true;
        }
        d("--->>>>>>>>---numberText：" + numberText);
        if (TextUtils.isEmpty(numberText)) {
            tv_card_number_error.setVisibility(View.VISIBLE);
            b = true;
        }
        d("--->>>>>>>>---cardName：" + cardName);
        if (TextUtils.isEmpty(cardName)) {
            tv_card_name_error.setVisibility(View.VISIBLE);
            b = true;
        }
        d("--->>>>>>>>---cardExp：" + cardExp);
        d("--->>>>>>>>---cvvText：" + cvvText);

        if (cb_card_visa.isChecked()) {
            if (TextUtils.isEmpty(cvvText)) {
                tv_card_mm_error2.setVisibility(View.VISIBLE);
                b = true;
            }
        } else {
            if (TextUtils.isEmpty(cardExp) || TextUtils.isEmpty(cvvText)) {
                tv_card_mm_error.setVisibility(View.VISIBLE);
                b = true;
            }
        }
        if (b) {
            return;
        }

        Map<String, Object> map = MapHelper.newHashMap();
        map.put("member_id", UserInfo.getMemberId());
        map.put("card_number", numberText);
        if (thirdTopupType == ThirdTopupType.thirdtopup_by_creditcard) {//用信用卡充值我的账户
            map.put("credit_card_amount", amount);
            map.put("other_amount", amount);
        } else if (thirdTopupType == ThirdTopupType.thirdtopup_from_orderpayment_ins_by_creditcard) {//订单付款余额不足,用信用卡充值差额
            map.put("credit_card_amount", amount);
//            map.put("other_amount", amount);
            map.put("checkout_log_id", getCheckout_log_id());
        } else if (thirdTopupType == ThirdTopupType.thirdtopup_from_orderpayment_by_creditcard) {//订单付款用信用卡付款
            map.put("checkout_log_id", getCheckout_log_id());
        }
        map.put("save_credit_card", saveCreditCard);
        map.put("name_on_card", cardName + "");
        map.put("expiration_date", cardExp + "");
        map.put("cvv", cvvText + "");
        getPresenter().validateTopup(map, thirdTopupType);
    }

    @Override
    protected void initEvent() {
        tv_card_amount_error.setBindEditText(et_card_amount);
        tv_card_number_error.setBindEditText(et_card_number);
        tv_card_name_error.setBindEditText(et_card_name);
        tv_card_mm_error2.setBindEditText(et_card_cvv2);
        tv_card_mm_error.setBindEditText(et_card_cvv);
        popupWindowYear.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                popupWindowYear.dismiss();
                yearAdapter.setSelectPosition(position);
                yyText = yearAdapter.getSelectItemText();
                tv_card_mm_error.setVisibility(View.GONE);
                tv_card_yy.setText(yyText);
            }
        });
        popupWindowMonth.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                popupWindowMonth.dismiss();
                monthAdapter.setSelectPosition(position);
                mmText = monthAdapter.getSelectItemText();
                tv_card_mm_error.setVisibility(View.GONE);
                tv_card_mm.setText(mmText);
            }
        });

        et_card_number.addTextChangedListener(new BaseTextWatcher() {
            @Override
            public void onTextChanged(CharSequence charSequence, int start, int count, int after) {
                super.onTextChanged(charSequence, start, count, after);
                String numberText = et_card_number.getText().toString().trim();
                String numberCardType = getPresenter().getNumberCardType(numberText);
                if (TextUtils.isEmpty(numberCardType)) {
                    iv_card_cardicon.setVisibility(View.GONE);
                } else {
                    iv_card_cardicon.setVisibility(View.VISIBLE);
                    iv_card_cardicon.setImageResource(TextUtils.equals(numberCardType, "Visa") ? R.drawable.icon_visa : R.drawable.ic_master);
                }
            }
        });

    }

    @OnClick({
            R.id.bt_card_submit,
            R.id.tv_card_mm,
            R.id.tv_card_yy,
            R.id.ll_card_selectcard,
            R.id.ll_card_newcard,
            R.id.iv_cvv_notice,
            R.id.iv_cvv2_notice,
            R.id.cb_card_visa,
            R.id.cb_card_newcard
    })
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_cvv_notice:
            case R.id.iv_cvv2_notice:
                ToastUtil.showToast(getString(R.string.topup_card_cvv_notice));
                break;
            case R.id.ll_card_selectcard:
                setHasCardGone(true);
                break;
            case R.id.ll_card_newcard:
                setHasCardGone(false);
                break;
            case R.id.cb_card_visa:
                setHasCardGone(true);
                break;
            case R.id.cb_card_newcard:
                setHasCardGone(false);
                break;
            case R.id.tv_card_mm:
                PopupWindowHelper.showPopupWindow(popupWindowMonth);
                break;
            case R.id.tv_card_yy:
                PopupWindowHelper.showPopupWindow(popupWindowYear);
                break;
            case R.id.bt_card_submit:
                submit();
                break;
            default:
                break;
        }
    }

    @Override
    public void validateTopupResult(ResultModel resultModel, Map<String, Object> map) {
        if (resultModel.isSuccess()) {
            Intent intent = new Intent(getContext(), TopupThirdActivity.class);
            intent.putExtra("map", (Serializable) map);
            intent.putExtra(CommonConstant.TOPUP_THIRDTOPUPTYPE, thirdTopupType);
            if (getTopupInfoBean() != null) {
                intent.putExtra(CommonConstant.TopupInfoBean, getTopupInfoBean());
            }
            startActivity(intent);
        }
    }
}
